import { entryInfoUrl, entrySaveUrl, userInfoUrl, userUpdateeInfoUrl, workListUrl } from '../../../../api/individual'
import { post, formatDate, get } from '../../../../utils/index'
import WxValidate from '../../../../utils/WxValidate'
import Dialog from '@vant/weapp/dialog/dialog'

Page({
  data: {
    page: '',
    readonly: false,
    isEdit: false,
    bgList: ['blue-color-bg', 'yellow-color-bg', 'green-color-bg', 'pink-color-bg', 'purple-color-bg'],
    title: '工作经历',
    info: {},
    works: [],
    form: {},
    formError: {},
    startDatePopup: false,
    endDatePopup: false,
    currentDate: new Date().getTime(),
    maxDate: new Date().getTime(),
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      }
      if (type === 'month') {
        return `${value}月`
      }
      return `${value}日`
    }
  },
  async loadData () { // 获取人员信息
    const url = this.data.page === 'entry' ? entryInfoUrl : userInfoUrl
    let { data, data: { works } } = await post(url)
    if (data.status === 3 || data.status === 4) {
      const { data: { rows } } = await get(workListUrl, { page: 1, pageSize: 30 })
      rows.forEach(item => {
        item.job = item.dutyCode
        item.isDeleted = 0
      })
      works = rows
    }
    this.setData({ info: data, works })
  },
  save () { // 保存
    const { form, works, info, editIndex } = this.data
    if (!this.WxValidate.checkForm(form)) {
      const formError = this.WxValidate.formError
      this.setData({ formError })
      wx.showToast({ title: '信息填写有误，请检查', icon: 'none' })
      return
    }
    if (editIndex > -1) {
      works[editIndex] = form
    } else {
      works.push(form)
    }
    info.works = works
    this.submit()
  },
  async submit () { // 提交
    const { page } = this.data
    const url = page === 'entry' ? entrySaveUrl : userUpdateeInfoUrl
    await post(url, this.data.info)
    this.loadData()
    this.setData({ isEdit: false, editIndex: -1, title: '工作经历' })
  },
  addWork () { // 添加工作经历
    const form = {}
    this.setData({ form, isEdit: true, title: '添加工作经历' })
  },
  async addAgain () { // 继续添加
    const { form, works, info, editIndex, page } = this.data
    if (!this.WxValidate.checkForm(form)) {
      const formError = this.WxValidate.formError
      this.setData({ formError })
      wx.showToast({ title: '信息填写有误，请检查', icon: 'none' })
      return
    }
    if (editIndex > -1) {
      works[editIndex] = form
    } else {
      works.push(form)
    }
    info.works = works
    const url = page === 'entry' ? entrySaveUrl : userUpdateeInfoUrl
    await post(url, this.data.info)
    this.setData({ form: {}, isEdit: true, editIndex: -1, title: '添加工作经历' })
  },
  editWork ({ currentTarget }) { // 编辑工作经历
    if (this.data.readonly) {
      return
    }
    const { index } = currentTarget.dataset
    const form = this.data.works[index]
    this.setData({ form, isEdit: true, title: '编辑工作经历', editIndex: index })
  },
  delWork ({ target, detail }) { // 删除工作经历
    const { instance } = detail
    Dialog.confirm({
      message: '确定删除该工作经历吗？',
    }).then(() => {
      instance.close()
      const { index } = target.dataset
      if (this.data.info.status === 3 || this.data.info.status === 4) {
        this.data.works[index].isDeleted = 1
        this.data.info.works = this.data.works
      } else {
        this.data.works.splice(index, 1)
      }
      this.submit()
    }).catch(() => {
      instance.close()
      Dialog.close()
    })
  },
  companyNameChange ({ detail }) { // 工作单位
    this.setData({ 'form.companyName': detail })
  },
  jobChange ({ detail }) { // 职务
    this.setData({ 'form.job': detail })
  },
  startDateClick () { // 开始时间弹窗
    wx.hideKeyboard()
    this.setData({ startDatePopup: true })
  },
  startDateChange ({ detail }) { // 选择开始时间日期
    const startDate = formatDate(new Date(detail), 'yyyy-MM-dd')
    this.setData({ 'form.startDate': startDate })
    this.startDateClose()
  },
  startDateClose () { // 关闭开始时间
    this.setData({ startDatePopup: false })
  },
  endDateClick () { // 结束时间弹窗
    wx.hideKeyboard()
    this.setData({ endDatePopup: true })
  },
  endDateChange ({ detail }) { // 选择结束时间日期
    const endDate = formatDate(new Date(detail), 'yyyy-MM-dd')
    this.setData({ 'form.endDate': endDate })
    this.endDateClose()
  },
  endDateClose () { // 关闭结束时间
    this.setData({ endDatePopup: false })
  },
  onClickLeft () { // 返回
    if (this.data.isEdit) {
      this.setData({ isEdit: false, title: '工作经历' })
      this.loadData()
      return
    }
    wx.navigateBack({})
  },
  initValidator () { // 初始化验证器
    const rules = {
      startDate: { required: true },
      endDate: { required: true },
      companyName: { required: true },
      endDate: { required: true }
    }
    const messages = {
      startDate: { required: '请选择开始时间' },
      endDate: { required: '请选择结束时间' },
      companyName: { required: '请输入工作单位' },
      companyName: { required: '请输入职务' }
    }
    this.WxValidate = new WxValidate(rules, messages)
  },
  readonlyChange () { // 编辑资料
    this.setData({ readonly: false })
  },
  onLoad (options) {
    // page表示从哪个页面过来的, entry->入职； change->修改；me->我的
    const { page } = options
    const readonly = page === 'me'
    this.setData({ readonly, page })
    this.loadData()
    this.initValidator()
  }
})